package com.isoft.c2team3service2.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.isoft.c2team3service2.entity.UserMessage;

import com.isoft.c2team3service2.entity.UserMessageVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMessageMapper extends BaseMapper<UserMessage> {
    // 查询两个用户之间的会话（按时间倒序）
    @Select("""
        SELECT m.*, u.nick_name AS senderNickName, h.photourl AS senderPhotoUrl, s.is_read AS isRead
        FROM user_message m
        LEFT JOIN tb_login ul ON m.sender_id = ul.id
        LEFT JOIN tb_person u ON ul.id = u.id
        LEFT JOIN tb_head h ON ul.email = h.email
        LEFT JOIN user_message_status s ON m.id = s.message_id AND s.receiver_id = #{currentUserId}
        WHERE (m.sender_id = #{userId1} AND m.receiver_id = #{userId2})
           OR (m.sender_id = #{userId2} AND m.receiver_id = #{userId1})
        ORDER BY m.create_time DESC
        LIMIT #{limit} OFFSET #{offset}
        """)
    List<UserMessageVO> selectConversation(Integer userId1, Integer userId2, Integer limit, Integer offset);

    // 查询未回复的消息数（用于限制未关注用户的发送）
    @Select("""
        SELECT COUNT(1) FROM user_message m
        WHERE m.sender_id = #{senderId} AND m.receiver_id = #{receiverId}
          AND NOT EXISTS (
              SELECT 1 FROM user_message m2
              WHERE m2.sender_id = #{receiverId} AND m2.receiver_id = #{senderId}
                AND m2.create_time > m.create_time
          )
        """)
    Integer countUnrepliedMessages(Integer senderId, Integer receiverId);
}